package com.louisgeek.myscanlogin.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by louisgeek on 2018/8/25.
 */
public class RootTool {
    /**
     * 设备是否Root
     *
     * @return
     */
    public static boolean isRootAvailable() {
        String buildTags = android.os.Build.TAGS;
        if (buildTags != null && buildTags.contains("test-keys")) {
            return true;
        }
        //
        String[] allPath = System.getenv("PATH").split(":");
        List<String> allList = new ArrayList<>(Arrays.asList(allPath));
        //
        String[] pathArr = {"/sbin",
                "/system/bin",
                "/system/xbin",
                "/data/local/xbin",
                "/data/local/bin",
                "/system/sd/xbin",
                "/system/bin/failsafe",
                "/data/local",
                "/su/bin"
        };
        for (String path : pathArr) {
            if (!allList.contains(path)) {
                allList.add(path);
            }
        }
        for (String pathDir : allList) {
            File file = new File(pathDir, "su");
            if (file.exists()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否被授予Root
     *
     * @return
     */
    public static boolean isRootGranted() {
        if (isRootAvailable()) {
            Process process = null;
            try {
                process = Runtime.getRuntime().exec(new String[]{"su", "-c", "id"});
                BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String output = in.readLine();
                if (output != null && output.toLowerCase().contains("uid=0")) {
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (process != null) {
                    process.destroy();
                }
            }
        }
        return false;
    }
}
